package com.lhf.springcloud.controller;

import com.lhf.springcloud.Entity.StudentInfo;
import com.lhf.springcloud.exception.StorageFileNotFoundException;
import com.lhf.springcloud.service.StorangeServiceImpl;
import com.lhf.springcloud.utils.ExcelUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: FileUploadController
 * @Description:  实现文件上传
 * @Author: liuhefei
 * @Date: 2019/4/1
 * @blog: https://www.imooc.com/u/1323320/articles
 **/
@Controller

public class FileUploadController {
    @Autowired
    private StorangeServiceImpl storangeService;

    /**
     * 展示上传的所有文件
     * @param model
     * @return
     * @throws IOException
     */
    @GetMapping("/")
    @ApiOperation("")
    public String listUploadedFiles(Model model) throws IOException {
        return "uploadForm";
    }
    @RequestMapping(value = "/findAllData",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("查询所有学生数据")
    public Map findAllData(){
        List<StudentInfo> allData = storangeService.findAllData();
        Map map=new HashMap<>();
        map.put("code",0);
        map.put("msg","成功");
        map.put("count",allData.size());
        map.put("data",allData);
        return map;
    }
    @RequestMapping(value = "/findStudentByYear",method = RequestMethod.GET)
    @ApiOperation("通过年限查询学生")
    @ApiImplicitParam(name ="year",value = "用户输入的年限")
    @ResponseBody
    public Map findAllData(String year){
        List<StudentInfo> allData = storangeService.findStudentByYear(year);
        Map map=new HashMap<>();
        map.put("code",0);
        map.put("msg","成功");
        map.put("count",allData.size());
        map.put("data",allData);
        return map;
    }
    @RequestMapping(value = "/updateData",method = RequestMethod.GET)
    @ApiOperation("更新学生信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "value",value = "要更新的字段名"),
            @ApiImplicitParam(name = "id",value = "要更新的字段id"),
            @ApiImplicitParam(name = "field",value = "准备更新的新值")
    })
    public String updateData(String value,String id,String field){
        storangeService.updateData(value,id,field);
        return "redirect:/";
    }
    @GetMapping("/files")
    @ResponseBody
    @ApiOperation("文件下载")
    public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
        // 下载本地文件
        String fileName = "学生学籍信息表.xlsx".toString(); // 文件的默认保存名
        // 读到流中
        String c = System.getProperty("user.dir");
        InputStream inStream = new FileInputStream(c+"/excel/学生学籍信息表.xlsx");// 文件的存放路径
//        InputStream inStream = new FileInputStream("E:\\测试练习code2\\诊改\\ZG\\file-upload\\src\\main\\resources\\templates\\excel\\学生基础数据表.xlsx");// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        try {
            response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//文件上传
    @PostMapping("/")
    @ApiOperation("文件上传")
    @ApiImplicitParam(name = "file",value = "需要上传的文件")
    public String handleFileUpload(@RequestParam("file")MultipartFile file, RedirectAttributes redirectAttributes,Model model) throws UnsupportedEncodingException{
        if(file.isEmpty()) {
            return "redirect:/";
        }
        List<StudentInfo> list1= new ArrayList<>();
        try {
            InputStream inputStream = file.getInputStream();
            List<List<Object>> list = ExcelUtils.getCourseListByExcel(inputStream, file.getOriginalFilename());
            inputStream.close();

            for (int i = 1; i < list.size(); i++) {
                List<Object> courseList = list.get(i);

                StudentInfo course = new StudentInfo();
                if (courseList.size()==0){
                    break;
                }
                course.setStudentName(courseList.get(0).toString());
                course.setStudentNumber(courseList.get(1).toString());

                course.setDepartment(courseList.get(2).toString());
                course.setMajor(courseList.get(3).toString());
                course.setGrade(courseList.get(4).toString());
//                if (Double.valueOf(String.valueOf(courseList.get(5)))>100||Double.valueOf(String.valueOf(courseList.get(5)))<0){
//                    redirectAttributes.addFlashAttribute("message", "第"+i+"行学生成绩异常，请核对后上传!" );
//                    list1.clear();
//                    break;
//                }
                course.setAchievement(courseList.get(5).toString());
                course.setGender(courseList.get(6).toString());
                course.setIdCard(courseList.get(7).toString());
                list1.add(course);
                // 执行插入操作

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String s=null;
        if (list1.size()>0){
             s = storangeService.addCourse(list1);
            //model.addAttribute("messages",s);
        }
        redirectAttributes.addFlashAttribute("messages", s);
            return "redirect:/";  //重定向
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }


}
